﻿using System;
using System.Windows;
using System.Windows.Input;
using _3DTicTacToe.Core;
using _3DTicTacToe.Net;

namespace _3DTicTacToe
{
    internal partial class NetChatWindow : Window
    {
        private readonly NetGame _game;
        private static string _history;

        public void WriteMessage(Player sender, string message)
        {
            historyTextBox.Text += sender.Name + "> " + message + Environment.NewLine;
            _history = historyTextBox.Text;
            historyTextBox.ScrollToEnd();
        }

        public NetChatWindow()
        {
            InitializeComponent();
            historyTextBox.Text = _history;
        }

        public NetChatWindow(NetGame game)
            : this()
        {
            _game = game;
        }

        public void ChatMessageReceived(string message)
        {
            Dispatcher.Invoke(new Action<Player, string>(WriteMessage), _game.RemotePlayer, message);
        }

        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            WriteMessage(_game.LocalPlayer, chatTextBox.Text);
            _game.SendChatMessage(chatTextBox.Text);
            chatTextBox.Text = string.Empty;
        }

        private void chatTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Return) return;

            sendButton_Click(null, null);
        }
    }
}
